const express = require('express')
const router = express.Router()

const SuccessModel = require('../module/SuccessModel')
const ErrorModel = require('../module/ErrorModel')


// 导入multer模块
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })


// 整合 knex
// 导入模块 并且连接上 本机的数据库
const knex = require('../utiles/knex')
// const router = require('../router/heroRouter')

//导入jsonwebtoken
const jwt = require('jsonwebtoken')
const key = 'itheima'

// 注册一个 中间件(回调函数)
router.use((req, res, next) => {
    // console.log('hero的中间件')
    // console.log('req.headers', req.headers)
    // 获取token
    const token = req.headers.authorization
    // 校验token
    jwt.verify(token, key, (err, data) => {
        if (!err) {
            // 不出错 进到这里
            // console.log('data:', data)
            // 执行next
            next()
        } else {
            // 校验出错
            // 失败
            // console.log('err:', err)
            res.send(new ErrorModel({ msg: '请登录', code: 401 }))
        }
    })
})


//查询英雄
router.get('/all', (req, response) => {
    const {
        q
    } = req.query
    if (q === undefined) {
        knex('hero')
            .select('id', 'name', 'icon', 'title')
            .where({ isdel: 0 })
            .then(res => {
                // console.log(res.length)
                if (res.length === 0) {
                    response.send(new ErrorModel({
                        msg: '查询失败,请检查'
                    }))
                }
                response.send(new SuccessModel({
                    msg: '查询成功',
                    data: res
                }))
            })
    } else {
        knex('hero')
            .select('id', 'name', 'icon', 'title')
            .where('title', 'like', `%${q}%`)
            .andWhere({ isdel: 0 })
            .then(res => {
                // console.log(res.length)
                if (res.length === 0) {
                    response.send(new ErrorModel({
                        msg: '查询失败,请检查'
                    }))
                }
                response.send(new SuccessModel({
                    msg: '查询成功',
                    data: res
                }))
            })
    }
})

//添加英雄
router.post('/add', upload.single('icon'), (req, response) => {
    // response.setHeader('Access-Control-Allow-Origin', '*')
    const { file, body } = req
    const { name, title, desc } = body
    // console.log('file:', file)
    // console.log('body:', body)
    if (name === undefined || title === undefined || desc === undefined || file === undefined) {
        response.send(new ErrorModel({ msg: '添加失败' }))
    } else {
        knex('hero').insert({
            name,
            title,
            desc,
            icon: file.filename
        }).then(res => {
            // console.log(res)
            response.send(new SuccessModel({
                msg: '添加成功'
            }))
        })

    }
})

//修改英雄
router.post('/update', upload.single('icon'), (req, response) => {
    // response.setHeader('Access-Control-Allow-Origin', '*')
    const { file, body } = req
    const { name, title, desc, id } = body
    // console.log(name, title, id)
    if (name === undefined || title === undefined || id === undefined || desc === undefined || file === undefined) {
        response.send(new ErrorModel({
            msg: '修改失败,请检查'
        }))
    } else {
        knex('hero').update({
                name,
                title,
                desc,
                icon: file.filename
            })
            .where({ id })
            .andWhere({ isdel: 0 })
            .then(res => {
                console.log(res)
                if (res === 0) {
                    response.send(new ErrorModel({ msg: '修改失败,检查id' }))
                } else {
                    response.send(new SuccessModel({ msg: '修改成功' }))
                }
            })
    }

})

//英雄软删除
router.post('/delete', (req, response) => {
    const { id } = req.body
    if (!id) {
        return response.send(new ErrorModel({ msg: 'id有误,请重新输入' }))
    }
    knex('hero').update({ isdel: 1 })
        .where({ id, isdel: 0 })
        .then(res => {
            if (!res) {
                return response.send(new ErrorModel({ msg: '删除失败,请重新输入' }))
            }
            response.send(new SuccessModel({ msg: '删除成功👽' }))
        })
})


//英雄详情
router.get('/:id', (req, response) => {
    // response.send('success')
    const { id } = req.params
    if (id === undefined) {
        response.send(new ErrorModel({ msg: '查询失败,请检查id' }))
    } else {
        knex('hero').select('id', 'name', 'title', 'icon', 'desc')
            .where({ id })
            .andWhere({ isdel: 0 })
            .then(res => {
                // console.log('res:', res)
                if (res.length === 0) {
                    return response.send(new ErrorModel({ msg: '查询失败,请检查参数' }))
                }
                response.send({
                    msg: '查询成功',
                    data: res[0]
                })

            })
    }
})


module.exports = router